package com.shundr.shipper.order;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.shundr.shipper.R;
import com.shundr.shipper.base.BaseActivity;
import com.shundr.shipper.cargo.DeliverCargoActivity;
import com.shundr.shipper.cargo.MyCargoDetailActivity;
import com.shundr.shipper.cargo.adapter.OrderCargoAdapter;
import com.shundr.shipper.cargo.http.CargoRequest;
import com.shundr.shipper.cargo.model.MyCargoInfo;
import com.shundr.shipper.common.util.JsonUtil;
import com.shundr.shipper.common.util.LImageLoader;
import com.shundr.shipper.common.util.ProgressDialogHelper;
import com.shundr.shipper.common.util.ToastHelper;
import com.shundr.shipper.common.view.CListView;
import com.shundr.shipper.common.view.CListView.OnLoadMoreListener;
import com.shundr.shipper.common.view.CListView.OnRefreshListener;
import com.shundr.shipper.common.view.DialogDelete;
import com.shundr.shipper.common.view.DialogDelete.onDeleteListener;
import com.shundr.shipper.frame.constant.LContext;
import com.shundr.shipper.frame.http.LHttpRequest;
import com.shundr.shipper.frame.util.StringUtil;

/**
 * 订单列表
 * OrderListActivity
 * 
 * @author larry 2015-5-16 下午2:15:38 
 * @version 1.0.0
 *
 */
public class CreateOrderActivity extends BaseActivity {

	private ImageView ivFull;//车辆照片
	private TextView tvCarCode;
	private ImageView ivValidation;
	private TextView tvContactor;
	
	private CListView mListView;
	private RelativeLayout mLayoutNoContent;
	private TextView tvNoContent;
	private ImageView ivHope;
	
	private ImageLoader mImageLoader;
//	
	private static final int PAGE_SIZE = LContext.PAGE_SIZE;
	private int pageNo = 0;
//	
	private String mStatus = "1";
//	
	private OrderCargoAdapter mAdapter;
//	
	private List<MyCargoInfo> mList = new ArrayList<MyCargoInfo>();
	
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case CargoRequest.GET_MY_CARGO_LIST_SUCCESSED:
					@SuppressWarnings("unchecked")
					List<MyCargoInfo> infos = (List<MyCargoInfo>) msg.obj;
					if (infos != null) {
						if (infos.size() > 0) {
							if (pageNo == 0) {
								mList.clear();
								mListView.setVisibility(View.VISIBLE);
								mLayoutNoContent.setVisibility(View.GONE);
								if (infos.size() >= PAGE_SIZE) {
									mListView.setCanLoadMore(true);
									mListView.setAutoLoadMore(true);
									mListView.setCanRefresh(true);
								} else {
									mListView.setCanLoadMore(false);
									mListView.setAutoLoadMore(false);
									mListView.setCanRefresh(false);
								}
							}
							mList.addAll(infos);
							mAdapter.notifyDataSetChanged();
							if (pageNo == 0) {
								mListView.setSelection(0);
							}
							pageNo = pageNo + 1;
						} else {
							if (pageNo == 0) {
								mListView.setVisibility(View.GONE);
								mLayoutNoContent.setVisibility(View.VISIBLE);
							} else {
								ToastHelper.toastLong(mContext, "最后一页");
							}
						}
					}
					ProgressDialogHelper.dismiss();
					mListView.onRefreshComplete();
					mListView.onLoadMoreComplete();
					break;
				case LHttpRequest.REQUEST_FAILED:
					ProgressDialogHelper.dismiss();
					mListView.onLoadMoreComplete();
					mListView.onRefreshComplete();
					ToastHelper.toastShort(mContext, msg.obj.toString());
					break;

				default:
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_order);
		LContext.isOrdered = false;
		this.mImageLoader = ImageLoader.getInstance();
		initView();
		initTruck();
		onRefesh();
	}
	
	private void initView(){
		
		ivFull = (ImageView)findViewById(R.id.iv_car_full);
		tvCarCode=(TextView)findViewById(R.id.tv_car_code);
		ivValidation = (ImageView)findViewById(R.id.iv_validation);
		tvContactor = (TextView)findViewById(R.id.tv_contactor);
		
		mListView = (CListView) findViewById(R.id.lv_list);
		mLayoutNoContent = (RelativeLayout)findViewById(R.id.layout_no_content);
		tvNoContent = (TextView)findViewById(R.id.tv_no_content);
		tvNoContent.setText("您还没有货源");
		ivHope=(ImageView)findViewById(R.id.iv_hope);
		ivHope.setImageResource(R.drawable.iv_no_cargo);
		ivHope.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startActivityForResult(new Intent(mContext, DeliverCargoActivity.class), 888);
			}
		});
		
		mAdapter = new OrderCargoAdapter(mList, mContext);
		mListView.setAdapter(mAdapter);
		mListView.setCanLoadMore(false);
		mListView.setAutoLoadMore(false);
		mListView.setCanRefresh(true);
		mListView.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				pageNo = 0;
				new CargoRequest(mContext, mHandler).getMyCargoList(pageNo * PAGE_SIZE, PAGE_SIZE, mStatus, LContext.nullStr, LContext.nullStr);
			}
		});
		mListView.setOnLoadListener(new OnLoadMoreListener() {
			@Override
			public void onLoadMore() {
				new CargoRequest(mContext, mHandler).getMyCargoList(pageNo * PAGE_SIZE, PAGE_SIZE, mStatus, LContext.nullStr, LContext.nullStr);
			}
		});
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					Intent intent=new Intent(mContext, MyCargoDetailActivity.class);
					intent.putExtra("json", JsonUtil.toJson(mList.get(position-1)));
					startActivityForResult(intent, 500);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
		mListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					final int position, long id) {
				MyCargoInfo info = mList.get(position - 1);
				if(info!=null){
					final int cargoId=info.getCargoId(); 
					DialogDelete dialogDelete=new DialogDelete(mContext);
					dialogDelete.setOnDeleteListener(new onDeleteListener() {
						
						@Override
						public void delete() {
							new CargoRequest(mContext, new Handler(){

								@Override
								public void handleMessage(Message msg) {
									super.handleMessage(msg);
									switch (msg.what) {
									case CargoRequest.DELETE_CARGO_SUCCESSED:
										ToastHelper.toastShort(mContext, "删除成功");
										mList.remove(position-1);
										mAdapter.notifyDataSetChanged();
										if(mList.size() == 0){
											mListView.setVisibility(View.GONE);
											mLayoutNoContent.setVisibility(View.VISIBLE);
										}
										break;
									case LHttpRequest.REQUEST_FAILED:
						                ToastHelper.toastShort(mContext, msg.obj.toString());
										break;
									default:
										break;
									}
								}
								
							}).deleteMyCargo(cargoId);
						}
					});
					dialogDelete.show();
				}
				return true;
			}
		});
	}
	
	private void initTruck(){
		if(LContext.truckInfo == null){
			return;
		}
		try {
			mImageLoader.displayImage(LContext.truckInfo.getTruckPic(), ivFull,LImageLoader.mOptions);
			tvCarCode.setText(LContext.truckInfo.getTruckPlateNumber());
			if(StringUtil.isNull(LContext.truckInfo.getTruckerName())){
				tvContactor.setText("车主未知");
			}else{
				tvContactor.setText(LContext.truckInfo.getTruckerName());
			}
			
			if(LContext.truckInfo.getTruckValidationStatus() == 0){
				ivValidation.setVisibility(View.GONE);
			}else if(LContext.truckInfo.getTruckValidationStatus() == 1){
				ivValidation.setImageResource(R.drawable.iv_truck_validation_successed);
				ivValidation.setVisibility(View.VISIBLE);
			}else{
				ivValidation.setImageResource(R.drawable.iv_truck_validation_failed);
				ivValidation.setVisibility(View.GONE);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void onRefesh(){
		ProgressDialogHelper.show(mContext, "数据加载中,请稍后...");
		pageNo = 0;
		new CargoRequest(mContext, mHandler).getMyCargoList(pageNo * PAGE_SIZE, PAGE_SIZE, mStatus, LContext.nullStr, LContext.nullStr);
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		switch (resultCode) {
		case 888:
			pageNo = 0;
			new CargoRequest(mContext, mHandler).getMyCargoList(pageNo * PAGE_SIZE, PAGE_SIZE, mStatus, LContext.nullStr, LContext.nullStr);
			break;

		default:
			break;
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu_confirm, menu);
		menu.getItem(0).setTitle("发货");
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_confirm:
			//添加页面
			startActivityForResult(new Intent(mContext, DeliverCargoActivity.class), 888);
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
}
